package com.io.example.demoparent.service.netty.impl;


import com.io.example.demoparent.config.NettyConfig;
import com.io.example.demoparent.exception.MyException;
import com.io.example.demoparent.service.netty.PushService;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Service("pushService")
@Slf4j
public class PushServiceImpl implements PushService {


    @Autowired
    private RedisTemplate redisTemplate;



    @Override
    public void pushMsgToOne(String uid, String msg)  {
        ConcurrentHashMap<String, Channel> userChannelMap = NettyConfig.getUserChannelMap();
        Channel channel = userChannelMap.get(uid);
        if(!Objects.isNull(channel)){
            // 如果该用户的客户端是与本服务器建立的channel,直接推送消息
            channel.writeAndFlush(new TextWebSocketFrame(msg));
        }else {
            // 发布，给其他服务器消费  发布订阅
            /**
             *  NettyPushMessageBody pushMessageBody = new NettyPushMessageBody();
             *  pushMessageBody.setUid(uid);
             *  pushMessageBody.setMessage(msg);
             *  redisTemplate.convertAndSend("",msg);
             */
            throw  new MyException(0005,"发布，给其他服务器消费  发布订阅");

        }

    }
    @Override
    public void pushMsgToAll(String msg){
        log.info("发布，给其他服务器消费");
        /**
      redisTemplate.convertAndSend("xxxx",msg);
      NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
         **/

    }
}